<?php
namespace app\index\controller;
use think\Response;
use app\superadmin\model\Order;
use app\superadmin\model\OrderRefund;
use think\Db;
use WeChat\Contracts\Tools;

class Notify{
    
    
    public function refund(){
        $pay_config = [
            'appid' =>  'wx6b0bc166ece6d3ea',
            'mch_id'    =>  '1610714247',
            'mch_key'   =>  'nqfxiu9pomyjytkvctruv2o42r84g2ao',
        ];
        $pay = \We::WePayRefund($pay_config);
        $notify = Tools::xml2arr(file_get_contents("php://input"));
        if (!isset($notify['return_code']) || $notify['return_code'] !== 'SUCCESS') {
            return json(['code'=>1, 'msg'=>'初始化失败']);
        }
        
        if(!is_array($notify)){
            return json(['code'=>10, 'msg'=>'数据错误']);
        }
        
        if(!(array_key_exists('appid', $notify) && $notify['appid'] == $pay_config['appid'] && array_key_exists('mch_id', $notify) && $notify['mch_id'] == $pay_config['mch_id'] && array_key_exists('req_info', $notify))){
            return json(['code'=>20, 'msg'=>'商户数据错误']);
        }
        
        // 退款数据解密
        try{
            $data = openssl_decrypt(base64_decode($notify['req_info']), 'AES-256-ECB', strtolower(md5($pay_config['mch_key'])), OPENSSL_RAW_DATA);
            $notify['decode'] = Tools::xml2arr($data);
        }catch(\Exception $e){
            return json(['code'=>30, 'msg'=>'数据解密失败']);
        }
        
        if(!(array_key_exists('decode', $notify) && is_array($notify['decode']))){
            return json(['code'=>30, 'msg'=>'数据解密失败']);
        }
        
        if(!(array_key_exists('transaction_id', $notify['decode']) && array_key_exists('out_trade_no', $notify['decode']) && array_key_exists('refund_id', $notify['decode']) && array_key_exists('out_refund_no', $notify['decode']) && array_key_exists('total_fee', $notify['decode']) && array_key_exists('refund_fee', $notify['decode']) && array_key_exists('settlement_refund_fee', $notify['decode']) && array_key_exists('refund_status', $notify['decode']) && array_key_exists('refund_status', $notify['decode']))){
            return json(['code'=>40, 'msg'=>'数据异常']);
        }
        $order = (new Order)->where('code', $notify['decode']['out_trade_no'])->find();
        if(!$order){
            return json(['code'=>50, 'msg'=>'订单不存在']);
        }
        
        $refund_order = (new OrderRefund)->where('sn', $notify['decode']['out_refund_no'])->find();
        if(!$refund_order){
            return json(['code'=>50, 'msg'=>'退款订单不存在']);
        }
        
        if($refund_order->order_id != $order->id){
            return json(['code'=>50, 'msg'=>'退款订单与订单不对应']);
        }

        $success_response = new Response($pay->getNotifySuccessReply(), 200, ['Content-Type'=>'text/xml; charset=utf-8']);
        if($order->refund_status == 100 && $refund_order->status == 10){
            return $success_response;
        }
        Db::startTrans();
        try{
            if(config('app_debug')){
                $refund_order->notify = $notify;
                $refund_order->save();
            }
           
            $query_order = $pay->query(['out_refund_no'=>$refund_order->sn]);
            if(array_key_exists('return_code', $query_order) &&  $query_order['return_code'] == 'SUCCESS'){
                // 退款成功
                if(array_key_exists('refund_status_0', $query_order) && $query_order['refund_status_0'] == 'SUCCESS'){
                    $order->refund_status  = 100;
                    $order->status = 5;
                    $refund_order->status = 10;
                    $refund_order->thrid_sn = $query_order['refund_id_0'];
                    $order->save();
                    $refund_order->save();
                }else{
                    $order->refund_status  = -1;
                    $refund_order->status = -1;
                    $refund_order->thrid_sn = $query_order['refund_id_0'];
                    $order->save();
                    $refund_order->save();
                }
                Db::commit();
                return $success_response;
            }
            Db::commit();
            return json(['code'=>60,'msg'=>'订单查询失败']);
        }catch(\Exception $e){
            Db::rollback();
            return json(['code'=>999,'msg'=>$e->getMessage()]);
        }
    }
}